import myaxios from "axios";
import router from '@/router'
import { Notify } from "vant";
import { reqRefreshToken } from '@/api'
import { getToken, removeToken, setToken } from '@/utils/token'


const axios = myaxios.create({
    baseURL: '/v1_0',
    timeout: 10000,
    headers: {
    }
})

// 添加请求拦截器
axios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    if (getToken()?.length > 0 && config.headers.Authorization === undefined) {
        config.headers.Authorization = `Bearer ${getToken()}`
    }
    return config;
}, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
});

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    return response;
}, async function (error) {
    if (error.response.status == 401) {
        // Notify({ type: "warning", message: "登录过期，请重新登录" });
        // removeToken()
        // router.replace('/login')
        const res = await reqRefreshToken()
        setToken(res.data.data.token)
        error.config.headers.Authorization = `Bearer ${res.data.data.token}`
        return axios(error.config)
    }
    return Promise.reject(error);
});

export default axios